import { parse } from '@lib/url';
import MarkdownIt from '@lib/markdown-it';
import Router from 'next/router';
import * as React from 'react';

interface MarkdownProps {
	text: string;
	className?: string;
}

class Markdown extends React.Component<MarkdownProps, any> {
	private ref: React.RefObject<HTMLDivElement>;
	constructor(props: any) {
		super(props);
		this.ref = React.createRef();
	}

	public handleClick(e: MouseEvent) {
		if (e.currentTarget && e.currentTarget instanceof HTMLAnchorElement) {
			if (window.location.origin && e.currentTarget.href.indexOf(window.location.origin) === 0) {
				e.preventDefault();
				const as = e.currentTarget.href.substr(window.location.origin.length);
				Router.push(parse(as), as);
				return false;
			}
		}
	}

	public componentDidMount() {
		this.bindClickEvent();
	}
	public componentDidUpdate() {
		this.bindClickEvent();
	}

	private bindClickEvent() {
		const el = this.ref.current;
		if (el) {
			el.querySelectorAll('a').forEach(it => {
				it.removeEventListener("click", this.handleClick);
				it.addEventListener("click", this.handleClick, {
					passive: false
				});
			});
		}
	}

	public render() {
		return (
			<div
				ref={this.ref}
				className={this.props.className || ""}
				dangerouslySetInnerHTML={{
					__html: MarkdownIt.render(this.props.text)
				}}
			>
			</div>
		)
	}
}

export default Markdown;